package cn.com.czpb.client.module.personal.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import cn.com.czpb.client.R;
import cn.com.czpb.client.app.BaseFragment;
import cn.com.czpb.client.custorm.CustomProgressDialog;
import cn.com.czpb.client.model.news.EmptyEntityList;
import cn.com.czpb.client.module.personal.acticity.LoginActivity;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.ParamUtils;
import cn.com.czpb.client.utils.TUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/7/5.
 */

public class FindbackpwFragment extends BaseFragment {
    private static final String TAG = "FindbackpwFragment";
    @BindView(R.id.title_stilte_layout)
    TextView title_stilte_layout;
    @BindView(R.id.phone_et_findpw_fragment)
    EditText phone_et_findpw_fragment;
    @BindView(R.id.code_et_findpw_fragment)
    EditText code_et_findpw_fragment;
    private String phoneNumber;
    private String code;
    @BindView(R.id.tv_findpw_fragment)
    volatile TextView tv_findpw_fragment;
    @BindView(R.id.fpb_ll_veify)
    LinearLayout fpb_ll_veify;//验证码
    @BindView(R.id.reset_ll_findpw)
    LinearLayout reset_ll_findpw;//找回密码

    @BindView(R.id.pw_1_findpw)
    EditText pw_1_findpw;
    @BindView(R.id.pw_2_findpw)
    EditText pw_2_findpw;

    @BindView(R.id.right_stitle_layout)
    TextView right_stitle_layout;
    int type;
    private Timer timer;

    private String pw1;
    private String pw2;

    private int t = 60;
    private boolean isflag = false;
    private CustomProgressDialog dialog; // 载入中对话框
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 333: {
                    try {
                        tv_findpw_fragment.setText(t + "秒后重发");
                        t--;
                        if (t < 0) {
                            resetTimer();
                        }
                        disMissDialog();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                }
                break;
                case 444: {

//                    verifyCorrect();
                    TUtils.toast("验证成功");
                    findPwd(phoneNumber, pw1);

                }
                break;
                case 555: {
                    TUtils.toast("验证码错误");
                    code_et_findpw_fragment.setText("");

                    resetTimer();
                }
                break;
                case 445: {
                    TUtils.toast("验证码获取成功");

                    startTime();// 开启定时器
                }
                break;
                case 446: {
                    TUtils.toast("验证码获取失败");

                    resetTimer();
                }
                break;
            }
        }
    };

    @Override
    public int setMyContentView() {
        return R.layout.fragment_findpw;
    }

    @Override
    public void initView() {

    }

    @Override
    public void initData() {

    }

    @OnClick(R.id.ll_back)
    public void goBack(View view) {
        onDestroy();
        activity.finish();
//        ((LoginActivity) activity).toLoginFm();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        title_stilte_layout.setText("找回密码");
        Bundle bundle = getArguments();

        SMSSDK.registerEventHandler(new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    if (result == SMSSDK.RESULT_COMPLETE) {
                        //验证码获取成功
                        handler.sendEmptyMessage(445);
                    } else if (result == SMSSDK.RESULT_ERROR) {
                        handler.sendEmptyMessage(446);
                    }
                } else if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    if (result == SMSSDK.RESULT_COMPLETE) {
                        handler.sendEmptyMessage(444);
                    } else if (result == SMSSDK.RESULT_ERROR) {
                        handler.sendEmptyMessage(555);
                    }
                }
            }
        });

    }

//    private void verifyCorrect() {
//        right_stitle_layout.setText("完成");
//        isflag=true;
//        fpb_ll_veify.setVisibility(View.GONE);
//        reset_ll_findpw.setVisibility(View.VISIBLE);
//
//    }


    private void startTime() {

        phone_et_findpw_fragment.setEnabled(false);
        tv_findpw_fragment.setClickable(false);
        if (timer != null) {
            timer.cancel();
        }
        tv_findpw_fragment.setTextColor(getResources().getColor(R.color.white));
        timer = new Timer();
        TimerTask tt = new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(333);
            }
        };
        timer.schedule(tt, 0, 1000);

    }

    private void resetTimer() {
        disMissDialog();
        if (null != timer) {
            timer.cancel();
        }
        tv_findpw_fragment.setText("重新获取");
        tv_findpw_fragment.setClickable(true);
        tv_findpw_fragment.setTextColor(getResources().getColor(R.color.white));
        phone_et_findpw_fragment.setEnabled(true);
        t = 60;
    }

    @OnClick(R.id.tv_findpw_fragment)
    public void getCode(View view) {
        //验证码验证

        phoneNumber = phone_et_findpw_fragment.getText().toString().trim();
        if (phoneNumber == null || "".equals(phoneNumber)) {
            TUtils.toast("请输入手机号！");
            return;
        }
        if (phoneNumber.length() != 11) {
            TUtils.toast("手机号位数不对!");
            return;
        }
        tv_findpw_fragment.setClickable(false);
        SMSSDK.getVerificationCode("86", phoneNumber);

    }

    @OnClick(R.id.btn_login_fragment)
    public void Verify(View v) {

        String code = code_et_findpw_fragment.getText().toString().trim();
        if (code == null || "".equals(code)) {
            TUtils.toast("请输入验证码！");
            return;
        }
        //修改新密码
//            phoneNumber = phone_et_findpw_fragment.getText().toString().trim();

        pw1 = pw_1_findpw.getText().toString().trim();
        pw2 = pw_2_findpw.getText().toString().trim();
        if (pw1 == null || "".equals(pw1)) {
            TUtils.toast("请输入密码");
            return;
        }
        if (pw1.length() < 6) {
            TUtils.toast("密码不能太短");
            return;
        }
        if (pw1.length() > 12) {
            TUtils.toast("密码不能太长");
            return;
        }
        if (pw2 == null || "".equals(pw2)) {
            TUtils.toast("请输入确认密码");
            return;
        }
        if (!pw1.equals(pw2)) {
            TUtils.toast("俩次密码不一致！");
            pw_1_findpw.setText("");
            pw_2_findpw.setText("");
            return;
        }
        SMSSDK.submitVerificationCode("86", phoneNumber, code);
        showDialog();
        findPwd(phoneNumber, pw2);


    }


    private void findPwd(String phone, String newPw) {
        Map<String, String> map = new HashMap<>();
        map.put("mobile", phone);

        map.put("password", newPw);
        Factory.provideHttpService().findPw(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<EmptyEntityList, Boolean>() {
                    @Override
                    public Boolean call(EmptyEntityList emptyEntity) {

                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<EmptyEntityList>() {
                    @Override
                    public void call(EmptyEntityList emptyEntity) {
                        LogUtils.e("success--" + emptyEntity);
                        disMissDialog();
                        TUtils.toast(emptyEntity.msg);
                        activity.finish();
                    }

                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        Log.e(TAG, "throwable: " + throwable.getMessage());
                    }
                });
    }


    @Override
    public void onDestroy() {
        if (timer != null) {
            timer.cancel();
        }
        // 销毁回调监听接口
        SMSSDK.unregisterAllEventHandler();
        super.onDestroy();
    }


}
